import logging
from pathlib import Path
from datetime import datetime
import httpx

class SonicConn:
    def __init__(self, host):
        self.host = host
        self.token = ""

    def get_token(self, username, password):
        "返回token"
        data = {
            "username": username,
            "password": password,
        }
        headers = {"Content-Type": "application/json"}
        response = httpx.post(
            self.host + "/api/admin/login",
            data=data,
            headers=headers,
        )
        if response.ok:
            self.token = response.json()["data"]["access_token"]
            return self.token
        else:
            logging.error("认证错误：" + response.text)
            return None

    def _upload_attachment(self, file_object):
        headers = {"Admin-Authorization": self.token}
        response = httpx.post(
            self.host + "/api/admin/attachments/upload",
            files=file_object,
            headers=headers,
        )
        if response.ok:
            return response.json()
        else:
            logging.error("上传错误：" + response.text)
            return None

    def upload_local_attachment(self, file_path):
        file_path = Path(file_path)
        return self._upload_attachment(
            {
                "file": (
                    file_path.name,
                    file_path.read_bytes(),
                    "application/" + file_path.suffix[1:],
                )
            }
        )

    def upload_mem_attachment(self, file_name, content, file_type):
        return self._upload_attachment(
            {
                "file": (
                    file_name,
                    content,
                    "application/" + file_type,
                )
            }
        )

    def get_attachment_url_path(self, stem):
        now = datetime.now()
        return "/upload/{}/{:0=2}/{}".format(now.year, now.month, stem)
